<?php

namespace app\common\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;

class UserUpgrade extends Command
{
    protected function configure()
    {
        $this->setName('user_upgrade')
            ->setDescription('用户等级升级：基于团队总USDT投资与小分区USDT投资');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->writeln("🚀 [" . date('Y-m-d H:i:s') . "] 开始执行用户等级升级任务...");

        // 1. 获取启用的等级配置（按等级升序）
        $levelConfigs = Db::name('user_level')
            ->where('status', 1)
            ->order('level', 'asc')
            ->select()
            ->toArray();

        $output->writeln("等级：" . json_encode($levelConfigs, JSON_UNESCAPED_UNICODE));


        if (empty($levelConfigs)) {
            $output->writeln("❌ 未找到启用的等级配置！");
            return;
        }

        // 2. 获取所有正常用户
        $users = Db::name('user')
            ->where('status', 1)
            ->where('delete_time', null)
            ->field('id, pid, path, level, invite_code')
            ->select()
            ->toArray();

        if (empty($users)) {
            $output->writeln("❌ 无有效用户！");
            return;
        }

        $totalProcessed = 0;
        $upgradedCount = 0;

        foreach ($users as $user) {
            $totalProcessed++;
            $output->writeln("👤 处理用户 #{$user['id']} [邀请码: {$user['invite_code']}] (当前等级: {$user['level']})");

            try {
                // === 1. 获取该用户所有下级用户 ID（通过 path 字段快速查询）===
                $subUserIds = Db::name('user')->where('pid', $user['id'])->column('id');
                if (empty($subUserIds)) {
                    $output->writeln("  🚫 无团队成员");
                    continue;
                }

                // === 2. 计算每个直推团队的 USDT 投资总额 ===
                $directUsers = Db::name('user')
                    ->where('pid', $user['id'])
                    ->column('id');

                if (empty($directUsers)) {
                    $output->writeln("  🚫 无直推下级");
                    continue;
                }

                $teamUsdtList = [];
                $totalTeamUsdt = 0.0;

                foreach ($directUsers as $directId) {
                    // 获取该直推子树的所有用户
                    $subtreeIds = Db::name('user')->where('path', 'like', '%,' . $directId . ',%')->column('id');

                    $usdtSum = Db::name('user_investment')
                        ->whereIn('user_id', $subtreeIds)
                        ->where('status', 1) // 生效中
                        ->sum('usdt_amount') ?: 0.0;

                    $teamUsdtList[] = $usdtSum;
                    $totalTeamUsdt += $usdtSum;
                }

                // === 3. 计算小分区 USDT（去掉最大团队，即“大区”）===
                $bigZoneUsdt = max($teamUsdtList);
                $smallPartitionUsdt = $totalTeamUsdt - $bigZoneUsdt;

                $output->writeln("  📊 团队总 USDT: " . number_format($totalTeamUsdt, 2) . " USDT");
                $output->writeln("  🔺 大区 USDT: " . number_format($bigZoneUsdt, 2) . " USDT");
                $output->writeln("  ⚖️  小分区 USDT: " . number_format($smallPartitionUsdt, 2) . " USDT");

                // === 4. 尝试升级（从低到高，取最高可达到等级）===
                $newLevel = $user['level'];
                $achievedLevel = $user['level'];

                foreach ($levelConfigs as $config) {
                    if ($config['level'] <= $user['level']) continue;

                    $requiredTotal = $config['total_mint'] ?? 0.0;
                    $requiredSmall = $config['small_partition_mint'] ?? 0.0;

                    if ($totalTeamUsdt >= $requiredTotal && $smallPartitionUsdt >= $requiredSmall) {
                        $achievedLevel = $config['level'];
                        $output->writeln("  ✅ 满足等级 {$config['level']} 条件！");
                    } else {
                        $output->writeln("  🚫 不满足等级 {$config['level']}：需团队{$requiredTotal}/小分区{$requiredSmall}");
                        break; // 后续等级更高，不可能满足
                    }
                }

                // === 5. 执行升级 ===
                if ($achievedLevel > $user['level']) {
                    $updateData = [
                        'level' => $achievedLevel,
                        'upgrade_time' => time(), // 确保 user 表有此字段
                        'update_time' => time()
                    ];

                    Db::name('user')->where('id', $user['id'])->update($updateData);

                    $output->writeln("  🔺 成功升级至等级 {$achievedLevel}！");
                    $upgradedCount++;
                } else {
                    $output->writeln("  🟢 当前等级已达标，无需升级。");
                }

            } catch (\Exception $e) {
                $output->writeln("  ❌ 异常: " . $e->getMessage());
            }

            $output->writeln(""); // 分隔
        }

        $output->writeln("✅ 升级任务完成！");
        $output->writeln("📊 共处理 {$totalProcessed} 名用户，成功升级 {$upgradedCount} 人。");
    }
}